package fr.generali.accueilclient.gwt.client.ui.components.table.renderer;

import com.google.gwt.resources.client.ImageResource;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.text.shared.AbstractSafeHtmlRenderer;
import com.google.gwt.user.client.ui.ImageResourceRenderer;

public class LinkOrImageRenderer extends AbstractSafeHtmlRenderer<String> {

    private ImageResource imageResource;

    public LinkOrImageRenderer(ImageResource imageResource) {
        this.imageResource = imageResource;
    }

    @Override
    public SafeHtml render(String object) {
        if (object == null || object.isEmpty()) {
            return new ImageResourceRenderer().render(imageResource);
        } else {
            AbstractSafeHtmlRenderer<String> renderer = new AbstractSafeHtmlRenderer<String>() {

                @Override
                public SafeHtml render(String object) {
                    return SafeHtmlUtils.fromString(object);
                }

                @Override
                public void render(String object, com.google.gwt.safehtml.shared.SafeHtmlBuilder appendable) {
                    appendable.append(render(object));
                };
            };

            String html =
                            new StringBuilder()
                                            .append("<div style=\"text-align:center;cursor:pointer;text-decoration:underline;\">")
                                            .toString();

            SafeHtmlBuilder sb = new SafeHtmlBuilder();
            sb.appendHtmlConstant(html);
            renderer.render(object, sb);
            sb.appendHtmlConstant("</div>");

            return sb.toSafeHtml();
        }
    }
}
